<template>
  <UI :form="form" :loading="loading" @send="sendCaptcha" @submit="register"  ></UI>
</template>

<script setup>
import UI from './ui/index.vue'
import { SEX } from '@enums/user'
import { useAuthStore } from '@/stores/modules/auth'  // 添加这行导入


import { registerCaptchaApi } from '@/api/auth'

const router = useRouter()

const authStore = useAuthStore()

const form = ref({
  avatar: '',
  nickname: '',
  sex: undefined, // 移除默认值，让用户必须选择
  email: '',
  captcha: '',
  password: '',
  confirmPassword: '',
})

const loading = ref(false)

const sendCaptcha = () => {
  const params = {
    email: form.value.email
  }
  registerCaptchaApi(params)
}
// 新增密码验证规则
const passwordRules = [
  (v) => !!v || '密码不能为空',
  (v) => v === form.value.confirmPassword || '两次输入的密码不一致'
]

const register = async () => {
  loading.value = true
  try {
    const registerData = {
      nickname: form.value.nickname,
      sex: form.value.sex,
      email: form.value.email,
      password: form.value.password,
      captcha: form.value.captcha,
      ...(form.value.avatar && { avatar: form.value.avatar })
    }
    
    const r = await authStore.register(registerData)
    if (r?.code === 200) {
      ElMessage.success(r.message || '注册成功')
      // 重置表单
      form.value = {
        avatar: '',
        nickname: '',
        sex: undefined,
        email: '',
        captcha: '',
        password: '',
        confirmPassword: ''
      }
      // 跳转到登录页
      router.push({ name: 'email-login' })
    }
  } catch (error) {
    ElMessage.error(error.message)
  } finally {
    loading.value = false
  }
}




</script>

<style lang="scss" scoped>
</style>
